package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.service.SpuService;
import com.changgou.pojo.*;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Goods findById(String id){

        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey( id );
        //查询sku列表
        Sku sku=new Sku();
        sku.setSpuId( id );
        sku.setIsDelete( "0" );
        List<Sku> skuList = skuMapper.select( sku );
        //封装到goods
        Goods goods=new Goods();
        goods.setSpu( spu );
        goods.setSkuList( skuList );
        return  goods;
    }

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 增加商品
     * @param goods
     */
    @Override
    @Transactional
    public void add(Goods goods){

        //保存spu
        Spu spu = goods.getSpu();
        String spuId = idWorker.nextId()+"";
        spu.setId( spuId );
        spuMapper.insertSelective( spu );

        //保存sku列表
        saveSkuList(goods);

        //添加分类与品牌的关联
        addCategoryBrand(spu.getCategory3Id(),spu.getBrandId());

    }

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * 添加分类与品牌的关联
     * @param categoryId
     * @param brandId
     */
    private void addCategoryBrand(Integer categoryId,Integer brandId){
        CategoryBrand categoryBrand=new CategoryBrand();
        categoryBrand.setBrandId( brandId );
        categoryBrand.setCategoryId( categoryId );
        int count = categoryBrandMapper.selectCount( categoryBrand );
        if(count==0){
            categoryBrandMapper.insert( categoryBrand );
        }
    }

    /**
     * 保存sku列表
     * @param goods
     */
    private void saveSkuList(Goods goods){
        Spu spu = goods.getSpu();
        Brand brand = brandMapper.selectByPrimaryKey( spu.getBrandId() );
        Category category = categoryMapper.selectByPrimaryKey( spu.getCategory3Id() );
        //保存sku列表
        List<Sku> skuList = goods.getSkuList();
        for(Sku sku:skuList){
            if(sku.getId()==null){
                sku.setId( idWorker.nextId()+"" );
            }
            sku.setSpuId( spu.getId() );
            sku.setCategory1Id( spu.getCategory1Id() );//1级分类
            sku.setCategory2Id( spu.getCategory2Id() );//2级分类
            sku.setCategory3Id( spu.getCategory3Id() );//3级分类
            sku.setBrandName( brand.getName() ); //品牌名称
            sku.setCategoryName( category.getName() );//分类名称
            //sku名称 规则： spu名称+规格值列表（空格分开）
            if(sku.getSpec()==null || "".equals( sku.getSpec() )){
                sku.setSpec( "{}" );
            }
            Map<String,String> specMap = JSON.parseObject( sku.getSpec(), Map.class );
            StringBuilder skuName= new StringBuilder( spu.getName() );
            for(String specValue:specMap.values()){
                skuName.append( " " +specValue );
            }
            sku.setName( skuName.toString() );
            sku.setCreateTime( new Date(  ) );
            sku.setUpdateTime( new Date(  ) );
            skuMapper.insertSelective( sku );
        }

    }

    /**
     * 修改
     * @param goods
     */
    @Override
    public void update(Goods goods){

        Spu spu = goods.getSpu();
        //修改spu
        spuMapper.updateByPrimaryKeySelective(spu  );

        //删除原sku列表
        Sku sku=new Sku();
        sku.setSpuId( spu.getId() );
        skuMapper.delete( sku );
        //添加sku列表
        saveSkuList( goods );

        //添加分类与品牌的关联
        addCategoryBrand( spu.getCategory3Id(),spu.getBrandId() );

    }

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional
    public void delete(String id){
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否下架的商品
        if(!spu.getIsMarketable().equals("0")){
            throw new RuntimeException("必须先下架再删除！");
        }
        spu.setIsDelete("1");//删除
        spu.setStatus("0");//未审核
        spuMapper.updateByPrimaryKeySelective(spu);
        //逻辑删除sku列表
        Sku sku=new Sku();
        sku.setIsDelete( "1" );

        Example example=new Example( Sku.class );
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "spuId",id );
        skuMapper.updateByExampleSelective( sku,example );
    }


    @Override
    @Transactional
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否删除的商品
        if(!"1".equals( spu.getIsDelete() )){
            throw new RuntimeException("此商品未删除！");
        }
        spu.setIsDelete("0");//未删除
        spu.setStatus("0");//未审核
        spuMapper.updateByPrimaryKeySelective(spu);
        //恢复sku列表逻辑删除
        Sku sku=new Sku();
        sku.setIsDelete( "0" );
        Example example=new Example( Sku.class );
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "spuId",id );
        skuMapper.updateByExampleSelective( sku,example );
    }

    @Override
    @Transactional
    public void realDelete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否删除的商品
        if(!spu.getIsDelete().equals("1")){
            throw new RuntimeException("此商品未删除！");
        }
        spuMapper.deleteByPrimaryKey(id);
        //删除sku列表
        Example example=new Example( Sku.class );
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "spuId",id );
        criteria.andEqualTo( "isDelete","1" );
        skuMapper.deleteByExample( example );
    }

    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    @Override
    public void audit(String id) {
        //查询
        Spu spu = spuMapper.selectByPrimaryKey( id );
        if(spu==null){
            throw  new RuntimeException( "商品不存在" );
        }
        if("1".equals( spu.getIsDelete() )){
            throw  new RuntimeException( "商品已删除" );
        }
        spu.setStatus( "1" );//审核
        spu.setIsMarketable( "1" );//上架
        spuMapper.updateByPrimaryKeySelective( spu );
    }


    @Override
    public void pull(String id) {
        Spu spu=new Spu();
        spu.setId( id );
        spu.setIsMarketable( "0" );
        spuMapper.updateByPrimaryKeySelective( spu);
    }

    @Override
    public void put(String id) {
        Spu spu = spuMapper.selectByPrimaryKey( id );
        if(spu==null){
            throw  new RuntimeException( "商品不存在" );
        }
        if("1".equals( spu.getIsDelete() )){
            throw  new RuntimeException( "商品已删除" );
        }
        if(!"1".equals(spu.getStatus())){
            throw  new RuntimeException( "商品未审核" );
        }
        spu.setIsMarketable( "1" );//上架
        spuMapper.updateByPrimaryKeySelective(  spu);
    }

    @Override
    public int putMany(String[] ids) {

        //修改的内容
        Spu spu=new Spu();
        spu.setIsMarketable( "1" );//上架状态

        //指定条件
        Example example=new Example( Spu.class );
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo( "isDelete","0" );//未删除
        criteria.andEqualTo( "status","1" );//必须审核通过的
        criteria.andIn( "id", Arrays.asList( ids ) ); //Id
        return spuMapper.updateByExampleSelective( spu,example );

    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andLike("sn","%"+searchMap.get("sn")+"%");
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("sale_service")!=null && !"".equals(searchMap.get("sale_service"))){
                criteria.andLike("sale_service","%"+searchMap.get("sale_service")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("spec_items")!=null && !"".equals(searchMap.get("spec_items"))){
                criteria.andLike("spec_items","%"+searchMap.get("spec_items")+"%");
           	}
            // 参数列表
            if(searchMap.get("para_items")!=null && !"".equals(searchMap.get("para_items"))){
                criteria.andLike("para_items","%"+searchMap.get("para_items")+"%");
           	}
            // 是否上架
            if(searchMap.get("is_marketable")!=null && !"".equals(searchMap.get("is_marketable"))){
                criteria.andLike("is_marketable","%"+searchMap.get("is_marketable")+"%");
           	}
            // 是否启用规格
            if(searchMap.get("is_enable_spec")!=null && !"".equals(searchMap.get("is_enable_spec"))){
                criteria.andLike("is_enable_spec","%"+searchMap.get("is_enable_spec")+"%");
           	}
            // 是否删除
            if(searchMap.get("is_delete")!=null && !"".equals(searchMap.get("is_delete"))){
                criteria.andLike("is_delete","%"+searchMap.get("is_delete")+"%");
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
